#  倾斜图片扶正
import cv2
import numpy as np


def deskew_image(image_path):
    # 读取图像
    image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
    # print(type(image))

    # 使用 Canny 边缘检测
    edges = cv2.Canny(image, 50, 150, apertureSize=3)

    # 使用霍夫变换检测直线
    lines = cv2.HoughLinesP(edges, 1, np.pi / 180, threshold=100, minLineLength=100, maxLineGap=10)

    if lines is not None:
        angles = []
        for line in lines:
            x1, y1, x2, y2 = line[0]
            angle = np.arctan2(y2 - y1, x2 - x1) * 180 / np.pi
            angles.append(angle)

        # 计算平均角度
        median_angle = np.median(angles)

        # 旋转图像
        (h, w) = image.shape[:2]
        center = (w // 2, h // 2)
        M = cv2.getRotationMatrix2D(center, median_angle, 1.0)
        rotated = cv2.warpAffine(image, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)

        return rotated
    else:
        return image



def deskew_image_aa(image):
    # 读取图像
    # image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
    print(type(image))

    # 使用 Canny 边缘检测
    edges = cv2.Canny(image, 50, 150, apertureSize=3)

    # 使用霍夫变换检测直线
    lines = cv2.HoughLinesP(edges, 1, np.pi / 180, threshold=100, minLineLength=100, maxLineGap=10)

    if lines is not None:
        angles = []
        for line in lines:
            x1, y1, x2, y2 = line[0]
            angle = np.arctan2(y2 - y1, x2 - x1) * 180 / np.pi
            angles.append(angle)

        # 计算平均角度
        median_angle = np.median(angles)

        # 旋转图像
        (h, w) = image.shape[:2]
        center = (w // 2, h // 2)
        M = cv2.getRotationMatrix2D(center, median_angle, 1.0)
        rotated = cv2.warpAffine(image, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)

        return rotated
    else:
        return image

# 调用函数
# image_path = ('C:\\Users\\kaifacs\\Desktop\\F863E7C4-E101-445f-99F5-9D3D4A2DBFE0.png')
#
# corrected_image = deskew_image(image_path)
#
# # 保存校正后的图像
# cv2.imwrite('C:\\Users\\kaifacs\\Desktop\\u_1_13.jpg', corrected_image)
#
# # 显示原图和校正后的图像
# cv2.imshow('Original Image', cv2.imread(image_path))
# cv2.imshow('Corrected Image', corrected_image)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
